var table;
$(function () {
    initDateRangePicker();
    loadOption();
});

/**
 * 加载地区下拉框数据
 */
function loadOption() {
    var url = baseRegionUrl + "list/region?start=0&limit=1000000";
    $.ajax(ajaxCommon.buildLoadingOption({
        url: url,
        headers: {
            "authorization": 'Bearer ' + getCookie(cookieName)
        },
        type: "GET",
        contentType: "application/json",
        success: function (data) {
            var arr = [];
            $(data.data.rows).each(function (index, obj) {
                var region = {"id": obj.id, "text": obj.name};
                arr.push(region);
            });
            $('#region').select2({
                data: arr
            });
            loadTable();
        },
        error: function (request, error) {
            if (request.status === 401) {
                $(location).attr('href', 'login.html');
            } else {
                swal("失败");
            }
        }
    }));
}

function loadTable() {
    var region = $('#region').val();
    var dateInterval = $("#reservation").val().split(" - ");
    var startDate = Date.parse(dateInterval[0]);
    var endDate = Date.parse(dateInterval[1]);
    var keyword = $("#keyword").val();
    var data = {region: region,startDate: startDate, endDate: endDate, search: keyword};
    table = $("#unQuestionList").DataTable({
        ajax: {
            url: baseStatisticalUrl + "list/unMatchQuestion",
            headers: {
                "authorization": 'Bearer ' + getCookie(cookieName)
            },
            type: "GET",
            contentType: "application/json",
            data: function (req) {
                req.limit = 15;
                req.search = data.search;
                req.startDate = data.startDate;
                req.endDate = data.endDate;
            },
            dataSrc: function (res) {
                res.recordsTotal = res.data.total;
                res.recordsFiltered = res.data.total;
                return res.data.rows;
            },
            error: function (request, error) {
                if (request.status === 401) {
                    $(location).attr('href', 'login.html');
                } else {
                    swal("失败");
                }
            }
        },
        serverSide: true,
        // data: data,
        destroy: true,
        bLengthChange: false,
        searching: false,
        ordering: false,
        select: false,
        columns: [
            {
                data: 'id',
                render: function(data, type, row, meta){
                    return 11-data;
                }
            },
            {data: 'question'},
            {
                data: 'created',
                render: function (data, type, row, meta) {
                    return formatDate1(row.created);
                }
            }
        ],
        pagingType: "full_numbers",
        language: {
            "sProcessing": "处理中...",
            "sLengthMenu": "显示 _MENU_ 项结果",
            "sZeroRecords": "没有匹配结果",
            "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
            "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
            "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
            "sInfoPostFix": "",
            "sSearch": "搜索:",
            "sUrl": "",
            "sEmptyTable": "表中数据为空",
            "sLoadingRecords": "载入中...",
            "sInfoThousands": ",",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "上页",
                "sNext": "下页",
                "sLast": "末页"
            },
            oAria: {
                "sSortAscending": ": 以升序排列此列",
                "sSortDescending": ": 以降序排列此列"
            }
        }
    });
}

function initDateRangePicker() {
    var date = new Date();
    if(date.getMonth() > 0) {
        $('input[name="daterange"]').daterangepicker({
                locale: {
                    format: 'YYYY-MM-DD'
                },
                startDate: date.getFullYear() + "-" + formNumber(date.getMonth()) + formNumber(date.getDate()),
                endDate: date.getFullYear() + "-" + formNumber(date.getMonth() + 1) + '-' + formNumber(date.getDate())
            },
            function (start, end, label) {
                //                        alert("A new date range was chosen: " + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD'));
            });
    } else {
        $('input[name="daterange"]').daterangepicker({
                locale: {
                    format: 'YYYY-MM-DD'
                },
                startDate: date.getFullYear() - 1 + "-" + formNumber(date.getMonth() + 12) + formNumber(date.getDate()),
                endDate: date.getFullYear() + "-" + formNumber(date.getMonth() + 1) + '-' + formNumber(date.getDate())
            },
            function (start, end, label) {
                //                        alert("A new date range was chosen: " + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD'));
            });
    }
}

/**
 * 查询按钮点击事件
 */
function queryData() {
    // var dateInterval = $("#reservation").val().split(" - ");
    // var startDate = Date.parse(dateInterval[0]);
    // var endDate = Date.parse(dateInterval[1]);
    // var keyword = $("#keyword").val();
    // var url = baseStatisticalUrl + "list/unMatchQuestion";
    // $.ajax(ajaxCommon.buildLoadingOption({
    //     url: url,
    //     type: "POST",
    //     contentType: "application/json",
    //     data: JSON.stringify({"startDate": startDate, "endDate": endDate, "keyword": keyword}),
    //     success: function (data) {
    var keyword = $("#keyword").val();
    loadTable(/*data.data.rows*/);
    //     },
    //     error: function (data) {
    //         alert("失败");
    //     }
    // }));
}

/**
 * 清除搜索条件
 */
function clearSelect() {
    $("#keyword").val("");
    initDateRangePicker();
    loadTable();
}

/**
 * 导出为Excel
 */
function exportExcel() {
    var dateInterval = $("#reservation").val().split(" - ");
    var startDate = Date.parse(dateInterval[0]);
    var endDate = Date.parse(dateInterval[1]);
    var keyword = $("#keyword").val();
    var url = baseStatisticalUrl + "export/unMatchQuestion?start=0&limit=1000000";
    $.ajax(ajaxCommon.buildLoadingOption({
        url: url,
        headers: {
            "authorization": 'Bearer ' + getCookie(cookieName)
        },
        type: "POST",
        contentType: "application/json",
        data: JSON.stringify({"startDate": startDate, "endDate": endDate, "keyword": keyword}),
        success: function (data) {
            if (data.data.length <= 0) {
                swal("当前数据为空");
                return;
            }
            var sheetData = [];
            $(data.data).each(function (index, obj) {
                var date = formatDate(new Date, obj.created);
                var d = {"id": obj.id, "question": obj.question, "created": date};
                sheetData.push(d);
            });
            var option = {};
            option.fileName = "未匹配问题(" + $("#reservation").val().split(" - ") + ")";
            option.datas = [
                {
                    sheetData: sheetData,
                    sheetName: 'unMatchQuestion',
                    sheetFilter: ['question', "created"],
                    sheetHeader: ['问题', '时间']
                },
                {
                    sheetData: sheetData
                }
            ];
            var toExcel = new ExportJsonExcel(option);
            toExcel.saveExcel();
        },
        error: function (request, error) {
            if (request.status === 401) {
                $(location).attr('href', 'login.html');
            } else {
                swal("失败");
            }
        }
    }));
}
